package com.bzxgc.sgwer.controller.user;

import com.bzxgc.sgwer.common.page.Constant;
import com.bzxgc.sgwer.common.util.JsonResult;
import com.bzxgc.sgwer.common.util.PageData;
import com.bzxgc.sgwer.entity.user.User;
import com.bzxgc.sgwer.entity.user.UserRole;
import com.bzxgc.sgwer.service.user.UserRoleService;
import com.bzxgc.sgwer.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;

    @RequestMapping("/ajax/login")
    @ResponseBody
    public JsonResult login(@RequestParam("loginName") String loginName, @RequestParam("password") String password, HttpSession session, HttpServletResponse response) {
        try {
            User user = userService.getUserByLoginName(loginName);
            if (user == null || !password.equals(user.getPassword())) {
                return JsonResult.error("登录失败，用户名或密码错误");
            }
            session.setAttribute("user", user);
            Cookie cookie = new Cookie("JSESSIONID", session.getId());
            cookie.setMaxAge(60 * 30);
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonResult.success("登录成功！");
    }

    @RequestMapping("/ajax/logout")
    @ResponseBody
    public JsonResult logout(HttpSession session) {
        session.removeAttribute("user");
        return JsonResult.success("退出成功！");
    }

    @RequestMapping("/add")
    public String add() {
        return "user/save";
    }

    @RequestMapping("/update/{id}")
    public String update(@PathVariable("id") Long id, HttpServletRequest request) {
        User user = userService.getUserById(id);
        request.setAttribute("user", user);
        return "user/save";
    }

    @RequestMapping("/ajax/save")
    @ResponseBody
    public JsonResult ajaxSave(User user) {
        if (user.getId() == null) {
            userService.addUser(user);
        } else {
            userService.updateUser(user);
        }
        return JsonResult.success("保存成功");
    }

    @RequestMapping("/ajax/delete")
    @ResponseBody
    public JsonResult ajaxDelete(@RequestParam("ids") Long[] ids) {
        userService.updateUserStatus(ids, 2);
        return JsonResult.success("删除成功");
    }

    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        int pageNum = Constant.DEFAULT_PAGE_NUM;
        String pageNumStr = request.getParameter("pageNum");
        if (pageNumStr != null && !pageNumStr.equals("")) {
            pageNum = Integer.parseInt(pageNumStr); // 显示第几页数据
        }

        int pageSize = Constant.DEFAULT_PAGE_SIZE;
        String pageSizeStr = request.getParameter("pageSize");
        if (pageSizeStr != null && !pageSizeStr.equals("")) {
            pageSize = Integer.parseInt(pageSizeStr); // 每页显示多少条记录
        }

        String name = request.getParameter("name");
        PageData<User> pageData = userService.getUserListByPage(pageNum, pageSize, name);
        request.setAttribute("pageData", pageData);
        request.setAttribute("name", name);
        return "/user/list";
    }

    /**
     * 查询所有用户
     * @return
     */
    @RequestMapping("/ajax/all")
    @ResponseBody
    public JsonResult all() {
        List<User> userList = userService.getAllUser();
        return JsonResult.success(userList);
    }

    @RequestMapping("/role/setting")
    public String menuSetting() {
        return "user/role-setting";
    }

    @RequestMapping("/ajax/save/setting")
    @ResponseBody
    public JsonResult ajaxMenuSetting(@RequestParam("userIds") Long[] userIds, @RequestParam("roleIds") Long[] roleIds, @RequestParam("roleId") Long roleId) {
        userRoleService.addUserRoleBatch(userIds, roleIds, roleId);
        return JsonResult.success("分配成功");
    }

    @RequestMapping("/ajax/role")
    @ResponseBody
    public JsonResult ajaxRoleSetting(@RequestParam("userId") Long userId) {
        List<UserRole> roleMenuList = userRoleService.getUserRoleByUserId(userId);
        return JsonResult.success(roleMenuList);
    }
}
